<?php

namespace app\api\controller;

use app\api\controller\Tpmecms;
use think\Db;

/**
 * 活动🎡
 */
class Act extends Tpmecms
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['test'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];


    /**
     * 获取我发布活动列表
     *
     * @param integer $page 1
     * @param integer $limit 10
     * @return void
     */
    public function get_my_list($page=1,$limit=5)
    {
        $list = Db::name('act')->where('uid',$this->auth->id)->order('time desc')->select();
        if($list){
            foreach ($list as $key => &$val) {
                $val = $this->ChangeFieldActListData($val);
            }
        }

        $this->success('ok', $list);
    }

    /**
     * 获取我参与的活动列表
     *
     * @param integer $page 1
     * @param integer $limit 10
     * @return void
     */
    public function get_join_list($page=1,$limit=5)
    {
        $act_ids = Db::name('actusers')->where('uid',$this->auth->id)->order('time desc')->column('act_id');
        $list = [];
        if($act_ids){
            $list = Db::name('act')->where('id','in',$act_ids)->order('time desc')->page($page,$limit)->select();
            foreach ($list as $key => &$val) {
                $val = $this->ChangeFieldActListData($val);
            }
        }

        $this->success('ok', $list);
    }

    /**
     * 获取最近快要开始的活动
     *
     * @return void
     */
    public function get_lately()
    {
        $act_ids = Db::name('actusers')->where('uid',$this->auth->id)->order('time desc')->column('act_id');
        $val = [];
        if($act_ids){
            $val = Db::name('act')->where('id','in',$act_ids)->order('time asc')->where('e_time','>',time())->find();
            if($val){
                $val = $this->ChangeFieldActListData($val);
                $val['m_time'] = date('m-d H:i',$val['s_time']);
            }
     
         
        }

        $this->success('ok', $val);
    }

    /**
     * 发布活动
     *
     * @param string $title 发布标题
     * @param string $content 发布内容
     * @param string $addr 地址
     * @param string $addr_name 地址名
     * @param string $num 参与人数
     * @param string $sex 性别:1=男,2=女(0不限制)
     * @param string $s_time 开始时间
     * @param string $e_time 结束时间
     * @param string $lat 纬度
     * @param string $lng 经度
     * @param string $images 图集
     * @param string $school_status 参与人学校1=只限本校参加2=不限制
     * @return void
     */
    public function add_act($title=null,$content=null,$images=null,$addr=null,$addr_name=null,$num=null,$sex='0',$s_time=null,$e_time=null,$lat=null,$lng=null,$school_status='2')
    {

        $this->IsAddAct();//是否可以发布
        if($content || $title){

            $this->VerifyStr($title);//验证违禁词
            $this->VerifyStr($content);//验证违禁词
            $data['title'] = $title;
            $data['content'] = $content;
            $data['images'] = $images;
            $data['addr'] = $addr;
            $data['addr_name'] = $addr_name;
            $data['num'] = $num;
            $data['sex'] = $sex??'0';
            $data['s_time'] = strtotime($s_time);
            $data['e_time'] = strtotime($e_time);
            $data['lat'] = $lat;
            $data['lng'] = $lng;
            $data['have_num'] = 1;//

            $data['time'] = time();
            $data['uid'] = $this->auth->id;
            $data['school_status'] = $school_status;
            $data['school_id'] = $this->auth->school_id;

            $id = Db::name('act')->insertGetId($data);

            $act_user_data['act_id']= $id;
            $act_user_data['uid']= $this->auth->id;
            $act_user_data['time']= $id;
            Db::name('actusers')->insertGetId($act_user_data);

            $this->success('发布成功',$id);
        }else{
            $this->error('请上传一些内容');
        }
    }

    /**
     * 删除我的某个活动
     *
     * @param int $id 活动id
     * @return void
     */
    public function del_act($id)
    {
        $act = Db::name('act')->where('id',$id)->find();
        if(!$act){
                $this->error('该活动不存在');
        }
        if($act['uid']!=$this->auth->id){
            $this->error('你没有该活动');
        }
        Db::name('act')->where('id',$id)->delete();
        $this->DelActCommentByact_id($id);
        $this->success('删除成功');
    }



    /**
     * 删除我的评论
     *
     * @param int $id 评论id
     * @return void
     */
    public function del_me_comment($id)
    {
        $comment = Db::name('act_comment')->where('id',$id)->where('uid',$this->auth->id)->find();
        if(!$comment){
            $this->error('该评论不存在');
        }
        $ids = [$id];
        //删除下级评论
        $xia_ids = Db::name('act_comment')->where('top_id',$id)->column('id');
        if($xia_ids){
            $ids = array_merge($xia_ids,$ids);
            //在找下级
            $xia2_ids = Db::name('act_comment')->where('top_id','in',$xia_ids)->column('id');
            if($xia2_ids){
                $ids = array_merge($xia2_ids,$ids);
            }
        }
        
        $res = Db::name('act_comment')->where('id','in',$ids)->delete();
        $this->success('删除成功',$res);
    }



    // /**
    //  * 获取用户的信息
    //  *
    //  * @param int $uid 用户id
    //  * @return void
    //  */
    // public function get_user_data($uid)
    // {
    //     $user['user'] = Db::name('user')->where('id',$uid)->find();
    //     if(!$user['user']){
    //         $this->error('该用户不存在');
    //     }
    //     $user['follow'] = Db::name('fans')->where('fans_uid',$this->auth->id)->count();
    //     $user['fans'] = Db::name('fans')->where('uid',$this->auth->id)->count();
    //     $user['character'] = Db::name('character')->where('id','in',$user['user']['character_ids'])->column('name');//个性
    //     $user['school'] = Db::name('school')->where('id',$user['user']['school_id'])->value('name');//学校名
    //     $user['isfollow'] = $this->GetMyIsfollowUser($uid);

    //     $this->success('ok',$user);
    // }



    /**
     * 获取所有的活动列表
     *
     * @param integer $school_id 学校ID(可不传)
     * @param integer $page 1
     * @param integer $limit 10
     * @return void
     */
    public function get_act_list($school_id=null,$page=1,$limit=10)
    {
        $where = null;
        if($school_id)
        $where['school_id'] = $school_id;

        $list = Db::name('act')->where($where)->order('top_switch desc,time desc')->page($page,$limit)->select();
      
        if($list){
            foreach ($list as $key => &$val) {
                $val = $this->ChangeFieldActListData($val);
            }
        }
        $this->success('ok', $list);
    }

    /**
     * 获取用户的活动列表
     *
     * @param integer $uid 用户ID
     * @param integer $page 1
     * @param integer $limit 10
     * @return void
     */
    public function get_user_act_list($uid,$page=1,$limit=10)
    {
        $list = Db::name('act')->where('uid',$uid)->order('time desc')->page($page,$limit)->select();
        if($list){
            foreach ($list as $key => &$val) {
                $val = $this->ChangeFieldActListData($val);
            }
        }
        $this->success('ok', $list);
    }

    /**
     * 获取活动详情
     *
     * @param int $id 活动ID
     * @return void
     */
    public function get_data($id)
    {
        $val = Db::name('act')->where('id',$id)->find();
        if($val){
            $val = $this->ChangeFieldActData($val);
        }else{
            $this->error('该活动不存在');
        }
        $this->IncActViews($id);
        $this->success('ok', $val);

    }


    /**
     * 改变活动字段
     *
     * @param array $val 
     * @return void
     */
    protected function ChangeFieldActListData($val){
  
        $val['user'] = $this->GetUserData2($val['uid']);
        $val['m'] = date('n',$val['time']);
        $val['d'] = date('d',$val['time']);
        $val['comment_num'] = $this->GetActCommentNum($val['id']);
        $val['self_likes'] = $this->GetUserIsActlikes($val['id'],$this->auth->id);
        $val['actusers'] = $this->GetActusers($val['id']);
        $val['date_str'] = $this->TimeToStr($val['time']);
        $val['have_num'] = $val['have_num'] - 1;
        return $val;
    }

    /**
     * 获取活动报名用户
     *
     * @param int $act_id 活动id
     * @return void
     */
    protected function GetActusers($act_id,$limit=10){
        $list = [];
        $ids = Db::name('actusers')->where('act_id',$act_id)->column('uid');
        if($ids)
        $list = Db::name('user')->where('id','in',$ids)->field('nickname,avatar,id')->limit($limit)->orderRaw('field(id,'.implode(',',$ids).')')->select();
        return $list;

    }



     /**
     * 改变活动字段
     *
     * @param array $val 
     * @return void
     */
    protected function ChangeFieldActData($val){

        $val['user'] = $this->GetUserData2($val['uid']);
        $val['comment'] = $this->GetActCommentArray($val['id']);//获取活动评论列表
        $val['m'] = date('n',$val['time']);
        $val['d'] = date('d',$val['time']);
        $val['comment_num'] = $this->GetActCommentNum($val['id']);
        $val['self_likes'] = $this->GetUserIsActlikes($val['id'],$this->auth->id);
        $val['actusers'] = $this->GetActusers($val['id']);
        $val['date_str'] = $this->TimeToStr($val['time']);
        $val['have_num'] = $val['have_num'] - 1;

        $weekarray=array("日","一","二","三","四","五","六");
        $val['s_date'] = date('m-d H:i',$val['s_time'])."（星期".$weekarray[date("w",$val['s_time'])].')';
        $val['e_date'] = date('m-d H:i',$val['e_time'])."（星期".$weekarray[date("w",$val['e_time'])].')';


        return $val;
    }

    /**
     * 退出活动
     *
     * @param int $act_id 活动id
     * @return void
     */
    public function exit_act($act_id)
    {
        $data['act_id'] = $act_id;
        $data['uid'] = $this->auth->id;
        $res = Db::name('actusers')->where($data)->find();
        if(!$res){
            $this->error('你不在该活动里');
        }
        Db::name('actusers')->where('id',$res['id'])->delete();
        $this->DecActHaveNum($act_id);
        $this->success('退出成功');
    }

    /**
     * 加入活动
     *
     * @param int $act_id 活动id
     * @return void
     */
    public function join_act($act_id)
    {
        $data['uid'] = $this->auth->id;
        $act = $this->Verifyact_id($act_id);
        switch ($act['sex']) {
            case '1':
                if($this->auth->sex!=$act['sex']){
                    $this->error('只限制男性');
                }
                break;
            case '2':
                if($this->auth->sex!=$act['sex']){
                    $this->error('只限制女性');
                }
                break;
            default:
                # code...
                break;
        }


        switch ($act['school_status']) {
            case '1':
                if($this->auth->school_id!=$act['school_id']){
                    $this->error('只限本校人员参加');
                }
                break;
            case '2':
                break;
            default:
                # code...
                break;
        }

        if($act['num']<=($act['have_num']-1)){
            $this->error('人数已满');
        }


        $data['act_id'] = $act_id;

        $res = Db::name('actusers')->where($data)->find();
        if($res){
            $this->error('你已报名了',$res);
        }
        $data['time'] = time();
        $data['id'] = Db::name('actusers')->insertGetId($data);
        $this->IncActHaveNum($act_id);
        $this->success('报名成功',$data);
    }



    /**
     * 加活动参加人数
     *
     * @param int $act_id 活动
     * @return void
     */
    protected function IncActHaveNum($act_id){
        Db::name('act')->where('id',$act_id)->setInc('have_num');
    }


    /**
     * 减活动参加人数
     *
     * @param int $act_id 活动
     * @return void
     */
    protected function DecActHaveNum($act_id){
        Db::name('act')->where('id',$act_id)->setDec('have_num');
    }

    /**
     * 评论活动
     *
     * @param int $act_id 活动id
     * @param string $content 内容
     * @param string $images 图集(可不传)
     * @param int $comment_id 评论id(可不传)
     * @return void
     */
    public function add_comment($act_id,$content=null,$comment_id=null,$images=null)
    {
        $val = Db::name('act')->where('id',$act_id)->find();
        if(!$val){
            $this->error('该活动不存在');
        }

        $res = Db::name('actusers')->where('act_id',$act_id)->where('uid',$this->auth->id)->find();
        if(!$res){
            $this->error('你未报名该活动，不能评论',$res);
        }

        $where['act_id'] = $act_id;
        $this->VerifyStr($content);
        if($comment_id){

            $res = Db::name('act_comment')->where('id',$comment_id)->where($where)->find();
            if(!$res){
                $this->error('该评论不存在');
            }
            if($res['comment_id']>0){
                $where['top_id'] = $res['top_id'];
            }else{
                $where['top_id'] = $comment_id;
            }
            $where['comment_uid'] = $res['uid'];//被评论的用户id
        }
        $where['comment_id'] = $comment_id;
        $where['content'] = $content;
        $where['images'] = $images;
        $where['uid'] = $this->auth->id;
        $where['time'] = time();     

        $id = Db::name('act_comment')->insertGetId($where);


        // $this->AddMsg($uid,$status,$public_id,$user_id=null,$title=null);//类型:1=动态点赞,2=动态评论,3=提问点赞,4=提问评论,5=活动点赞,6=活动留言,7=聊天消息
        $this->AddMsg($val['uid'],6,$act_id,$this->auth->id,$this->auth->nickname.'给你活动留言了');

        $this->success('评论成功', $id);
    }


    
    /**
     * 修改点赞
     *
     * @param int $act_id 活动id
     * @return void
     */
    public function update_likes($act_id)
    {
       
        $data['uid'] = $this->auth->id;
        $data['act_id'] = $act_id;
        $act = Db::name('act')->where('id',$act_id)->find();
        $res = Db::name('actlikes')->where($data)->find();
        if(!$res){
            $data['time'] = time();
            if(!$act)$this->error('该活动不存在');
            // $data['act_uid'] = $act['uid'];
            $data['id'] = Db::name('actlikes')->insertGetId($data);
            //点赞数+1
            $this->IncActLikes($act_id);

             // $this->AddMsg($uid,$status,$public_id,$user_id=null,$title=null);//类型:1=动态点赞,2=动态评论,3=提问点赞,4=提问评论,5=活动点赞,6=活动留言,7=聊天消息
            $this->AddMsg($act['uid'],5,$act_id,$this->auth->id,$this->auth->nickname.'给你活动点赞了');


            $this->success('点赞成功',1);
        }else{
            Db::name('actlikes')->where('id',$res['id'])->delete();
            //点赞数-1
            $this->DecActLikes($act_id);

           
            // $this->AddMsg($act['uid'],5,$act_id,$this->auth->id,$this->auth->nickname.'给你活动取消点赞了');
            $this->success('取消点赞',0);
        }
    }



}
